import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:uuid/uuid.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart' as path;
import '../utils/imagePath.dart'; // 添加ImagePath工具类导入

/// 图片永久存储服务
class ImageStorageService {
  // 单例模式
  static final ImageStorageService _instance = ImageStorageService._internal();
  factory ImageStorageService() => _instance;
  ImageStorageService._internal();

  // 获取应用文档目录
  Future<Directory> get _app_doc_dir async {
    return await getApplicationDocumentsDirectory();
  }

  // 获取图片存储目录
  Future<Directory> get _image_dir async {
    final Directory app_dir = await _app_doc_dir;
    final Directory image_dir = Directory('${app_dir.path}/images');

    // 确保目录存在
    if (!await image_dir.exists()) {
      await image_dir.create(recursive: true);
    }

    return image_dir;
  }

  // 保存单个图片到永久存储
  Future<String> save_image(XFile image) async {
    try {
      final Directory img_dir = await _image_dir;
      final String file_name = '${Uuid().v4()}${path.extension(image.path)}';
      final String save_path = '${img_dir.path}/$file_name';

      // 复制图片到应用目录
      final File saved_image = await File(image.path).copy(save_path);
      debugPrint('图片已保存: $saved_image');

      // 将绝对路径转换为相对路径
      final String relative_path = await ImagePath.to_relative_path(save_path);
      debugPrint('相对路径: $relative_path');

      return relative_path;
    } catch (e) {
      debugPrint('保存图片失败: $e');
      return '';
    }
  }

  // 批量保存图片到永久存储，返回路径列表字符串（以逗号分隔）
  Future<String> save_images(List<XFile> images) async {
    List<String> saved_paths = [];

    for (XFile image in images) {
      final String path = await save_image(image);
      if (path.isNotEmpty) {
        saved_paths.add(path);
      }
    }

    return saved_paths.join(',');
  }

  // 从路径加载图片
  Future<File?> load_image_from_path(String image_path) async {
    try {
      // 如果是相对路径，先转换为绝对路径
      String actual_path = image_path;
      if (image_path.startsWith('app://')) {
        final absolute_path = await ImagePath.get_absolute_path(image_path);
        if (absolute_path != null) {
          actual_path = absolute_path;
        }
      }

      final File file = File(actual_path);
      if (file.existsSync()) {
        return file;
      }
      return null;
    } catch (e) {
      debugPrint('加载图片失败: $e');
      return null;
    }
  }

  // 从逗号分隔的路径字符串加载多个图片
  Future<List<File>> load_images_from_paths(String image_paths) async {
    if (image_paths.isEmpty) return [];

    List<File> files = [];
    final List<String> paths = image_paths.split(',');

    for (String path in paths) {
      if (path.trim().isNotEmpty) {
        final File? file = await load_image_from_path(path.trim());
        if (file != null) {
          files.add(file);
        }
      }
    }

    return files;
  }

  // 删除图片
  Future<bool> delete_image(String image_path) async {
    try {
      // 如果是相对路径，先转换为绝对路径
      String actual_path = image_path;
      if (image_path.startsWith('app://')) {
        final absolute_path = await ImagePath.get_absolute_path(image_path);
        if (absolute_path != null) {
          actual_path = absolute_path;
        }
      }

      final File file = File(actual_path);
      if (await file.exists()) {
        await file.delete();
        return true;
      }
      return false;
    } catch (e) {
      debugPrint('删除图片失败: $e');
      return false;
    }
  }
}
